<template>
  <div id="app">
    <el-button @click="dialogVisible = true" type="text">添加学生</el-button>
    <el-table :data="student_list" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="120"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="age" label="年龄" width="120"></el-table-column>
      <el-table-column prop="className" label="班级" width="300"></el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="del(scope.row.id)" type="text" size="small">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="item" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="item.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="item.age"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="item.className"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveStudent">立即创建</el-button>
          <el-button @click="dialogVisible = false">删除</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  methods: {
    del(id) {
      for(var i=0;i<this.student_list.length;i++){
        if(id == this.student_list[i]['id']){
          this.student_list.splice(i,1);
          break;
        }
      }
    },
    saveStudent() {
      this.item.id = this.student_list.length + 1;
      this.student_list.push(this.item);
      this.resetItem();
    },
    resetItem() {
      this.item = { id: 0, name: "", age: "", className: "" };
      this.dialogVisible = false;
    },
  },

  data() {
    return {
      student_list: [
        { id: 1, name: "张飞", age: 56, className: "1903" },
        { id: 2, name: "关羽", age: 46, className: "1902" },
        { id: 3, name: "赵云", age: 45, className: "1901" },
      ],
      data_list: [],
      item: { id: 0, name: "", age: "", className: "" },
      dialogVisible:false,
    };
  },
  mounted() {
    localStorage.setItem("student", this.student_list);
  },
};
</script>